package middleware

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"house123/C/api/internal/types"
	"house123/C/api/pkg"
	"net/http"
)

type JwtTokenMiddleware struct {
}

func NewJwtTokenMiddleware() *JwtTokenMiddleware {
	return &JwtTokenMiddleware{}
}

func (m *JwtTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		fmt.Println("触发了中间件")

		Token := r.Header.Get("token")
		if Token == "" {
			resp := &types.Response{
				Code: 10001,
				Msg:  "用户未登录",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		token, err := pkg.GetToken(Token)
		if err != nil {
			resp := &types.Response{
				Code: 10002,
				Msg:  "用户登录失败",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		context.WithValue(context.Background(), "UserId", token)
		// Passthrough to next handler if need
		next(w, r.WithContext(context.Background()))
	}
}
